package cn.tedu.boyou.search.service.impl;

import cn.tedu.boyou.search.query.SaleQueryObject;
import cn.tedu.boyou.search.repository.ISaleTemplateRepository;
import cn.tedu.boyou.search.service.ISaleSearchService;
import cn.tedu.boyou.search.template.SaleTemplate;
import com.alibaba.dubbo.config.annotation.Service;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class SaleSearchServiceImpl implements ISaleSearchService {

    @Autowired
    private ISaleTemplateRepository dao;

    @Autowired
    private ElasticsearchTemplate template;

    @Autowired
    private TransportClient client;

    public void createIndex() {
        template.createIndex(SaleTemplate.class);
        template.putMapping(SaleTemplate.class);
    }

    public void save(SaleTemplate t) {
        dao.save(t);
    }

    @Override
    public List<SaleTemplate> query(SaleQueryObject qo) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();

        Iterable<SaleTemplate> iterable = dao.search(boolQuery);
        ArrayList<SaleTemplate> list = new ArrayList<>();
        for (SaleTemplate saleTemplate : iterable) {
            list.add(saleTemplate);
        }
        return list;
    }

    @Override
    public Page<SaleTemplate> queryPage(SaleQueryObject qo) {

        Calendar calendar = Calendar.getInstance();

        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (qo.getState_schedule() != null){
            for (Date date : qo.getState_schedule()) {
                calendar.setTime(date);
                calendar.add(Calendar.MONTH,1);
                Date time = calendar.getTime();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = sdf.format(date);
                String timeStr = sdf.format(time);
                boolQuery.should(QueryBuilders.rangeQuery("state_schedule").
//                        from(qo.getState_schedule()).
//                        to(time)
                        from(dateStr).to(timeStr)
                );
            }
        }

        Page<SaleTemplate> page = dao.search(boolQuery, qo.getPageable());
        return page;
    }
}
